package edu.ucsd.cse135.gas.action.applicant;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.ucsd.cse135.gas.bean.applicant.NameForm;
import edu.ucsd.cse135.gas.logic.applicant.Applicant;
import edu.ucsd.cse135.gas.logic.support.Location;
import edu.ucsd.cse135.gas.resources.Constants;

public class NameAction extends Action {

	public NameAction() {
		super();
	}
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		
		NameForm nameForm = (NameForm)form;
		
		Applicant applicant = new Applicant();
	
		applicant.setFirstName(nameForm.getFirstName());
		applicant.setMiddleInitial(nameForm.getMiddleInitial());
		applicant.setName(nameForm.getName());
		applicant.setMail(request.getRemoteUser());
		
		request.getSession().setAttribute("applicant", applicant);
		
		Location locations = new Location();
		ArrayList<Location> countryList = new ArrayList<Location>();	
		countryList = locations.getCountries();
		
		ArrayList<HashMap<String, String>>  countriesCol1 = new ArrayList<HashMap<String, String>>();
		ArrayList<HashMap<String, String>>  countriesCol2 = new ArrayList<HashMap<String, String>>();
		ArrayList<HashMap<String, String>>  countriesCol3 = new ArrayList<HashMap<String, String>>();
							
		/*** Prepare auxiliary iterator 'col' to get a three-column format ***/
								
		int col = countryList.size()/3;
												
		/*** Iteration for column one ***/
							
		for(int i=0; i<col; i++)
		{
			HashMap<String, String> country = new HashMap<String, String>();
			
			country.put("name", countryList.get(i).getName());
			country.put("id", ""+countryList.get(i).getId());
			
			countriesCol1.add(country);
		}
					
		/*** Iteration for column two ***/
						
		for(int i=col; i<(col+col); i++)
		{
			HashMap<String, String> country = new HashMap<String, String>();
			
			country.put("name", countryList.get(i).getName());
			country.put("id", ""+countryList.get(i).getId());
			
			countriesCol2.add(country);
		}
							
									
		/*** Iteration for column three ***/
							
		for(int i=(col+col); i<countryList.size(); i++)
		{
			HashMap<String, String> country = new HashMap<String, String>();
			
			country.put("name", countryList.get(i).getName());
			country.put("id", ""+countryList.get(i).getId());
			
			countriesCol3.add(country);
		}
		
	
		request.setAttribute("countriesCol1", countriesCol1);
		request.setAttribute("countriesCol2", countriesCol2);
		request.setAttribute("countriesCol3", countriesCol3);
		
		return mapping.findForward(Constants.SUCCESS);
	}
	
}
